/*
 * Copyright (c) 2021 柯华栋
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "ipc_server.h"

typedef module_controller_t* (*get_controller)();

// 声明	
module_controller_t* mcu_get_controller();
module_controller_t* radio_get_controller();

// 控制器工厂方法
static module_controller_t* get_module_controller(const gchar* module_name)
{
	// 映射
	static id_pointer_map_t* id_fn = NULL;
	if (id_fn == NULL) {
		id_fn = id_pointer_map_new();
		id_pointer_map_set(id_fn, "mcu", 	mcu_get_controller);
		id_pointer_map_set(id_fn, "radio", 	radio_get_controller);
	}
	
	// 获取
	get_controller get = (get_controller) id_pointer_map_get(id_fn, module_name);
	return get == NULL ? NULL : get();
}

static gboolean test_server_update(gpointer data)
{
	(void)data;

	static int mcu_version = 0;
	static int radio_version = 123456;
	mcu_version++;
	radio_version++;
	
	gchar* str = g_strdup_printf("Version %d From Mcu Server", mcu_version);
	server_update(ipc_map_new_id_string("mcu.version", str));
	g_free(str);
	
	str = g_strdup_printf("Version %d From Radio Server", radio_version);
	server_update(ipc_map_new_id_string("radio.version", str));
	g_free(str);
	
	return TRUE;
}

int main()
{
	// !!!!! 非常重要
	ipc_init();
	
	// 设置控制器工厂方法
	server_set_module_controller_getter(get_module_controller);

	// 创建服务
	GDBusServer* server = server_new("mcu");
	
	g_timeout_add(1000, test_server_update, NULL);

	GMainLoop* loop = g_main_loop_new(NULL, FALSE);
	g_main_loop_run(loop);
	g_object_unref(server);
	g_main_loop_unref(loop);
}